package com.alibaba.citrus.cr.mn.order.center.facade.function.convert;

import com.alibaba.citrus.cr.b2b.trade.order.facade.common.SetOrderTag;
import com.alibaba.citrus.cr.common.constant.SaleOrderConstants;
import com.alibaba.citrus.cr.common.util.DateUtils;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.BaseDataServiceAdapter;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.epoch.app.bcorder.platform_enhance.SaleOrderTag;
import com.epoch.app.crb2btradecenter.enums.OrderStatus;
import com.epoch.app.crb2btradecenter.obtcsaleorderlineindex.model.ObtcSaleOrderLineIndex;
import com.epoch.app.crforecastsales.model.dto.ActivitySDO;
import com.epoch.app.crplatformenhance.model.dto.DictValueSDO;
import com.epoch.app.mnordercenter.model.dto.OrderLineSDO;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhoubc
 * @date 2023/5/25 19:52
 */

public class OrderLineIndexToOrderLineSDOConvertor {

    public static OrderLineSDO convert(ObtcSaleOrderLineIndex orderLine){
        OrderLineSDO orderLineSDO = new OrderLineSDO();
        orderLineSDO.setId(orderLine.getSubId() != null ? String.valueOf(orderLine.getSubId()) : null);
        if (StringUtils.isNotBlank(orderLine.getMainOrderType())) {
            String desc = SaleOrderTag.of(orderLine.getMainOrderType()).getDesc();
            orderLineSDO.setOrderType(orderLine.getMainOrderType());
            orderLineSDO.setOrderTypeName(desc);
        }
        orderLineSDO.setOrderId(orderLine.getMainId() != null ? String.valueOf(orderLine.getMainId()) : null);
        orderLineSDO.setOrderBizId(orderLine.getMainOrderBizId());
        orderLineSDO.setOuterOrderId(orderLine.getMainOuterOrderId());
        orderLineSDO.setOrderLineNo(orderLine.getSubSerialNumber());
        orderLineSDO.setOuterOrderLineId(orderLine.getSubOuterOrderLineId());
        orderLineSDO.setOrderLineTag(orderLine.getSubOrderLineTag());
        orderLineSDO.setScItemId(orderLine.getSubScItemId());
        orderLineSDO.setScItemTitle(orderLine.getSubScItemTitle());
        orderLineSDO.setScItemCode(orderLine.getSubScItemOutCode());
        orderLineSDO.setCustomerName(orderLine.getMainCustomerName());
        orderLineSDO.setCustomerCode(orderLine.getMainCustomerCode());
        orderLineSDO.setReceiveAddressCode(orderLine.getMainReceiveAddressCode());
        orderLineSDO.setReceiveDetailAddress(orderLine.getMainReceiveDetailAddress());
        orderLineSDO.setBisUnitCode(orderLine.getMainBisUnitOutCode());
        orderLineSDO.setBisUnitName(orderLine.getMainBisUnitName());
        orderLineSDO.setSalesOrganizationCode(orderLine.getMainOrganizationOutCode());
        orderLineSDO.setSalesOrganizationName(orderLine.getMainOrganizationName());
        orderLineSDO.setSalesChannelCode(orderLine.getMainSaleChannelOutCode());
        orderLineSDO.setSalesChannelName(orderLine.getMainSaleChannelName());
        orderLineSDO.setSalesDepartmentCode(orderLine.getMainDepartmentOutCode());
        orderLineSDO.setSalesDepartmentName(orderLine.getMainDepartmentName());
        orderLineSDO.setChannelCode(orderLine.getMainChannelCode());
        orderLineSDO.setChannelName(orderLine.getMainChannelName());
        orderLineSDO.setProductGroupCode(orderLine.getMainProductGroupCode());
        orderLineSDO.setProductGroupName(orderLine.getMainProductGroupName());
        orderLineSDO.setSaleUnit(orderLine.getSubSaleUnit());
        orderLineSDO.setSaleUnitName(orderLine.getSubSaleUnitName());
        orderLineSDO.setInventoryUnit(orderLine.getSubInventoryUnitCode());
        orderLineSDO.setInventoryUnitName(orderLine.getSubInventoryUnit());
        orderLineSDO.setUnitConvert(orderLine.getSubUnitConvert());
        if (orderLine.getSubStatus() != null) {
            String desc = OrderStatus.of(Integer.parseInt(String.valueOf(orderLine.getSubStatus()))).getDesc();
            orderLineSDO.setSubStatus(String.valueOf(orderLine.getSubStatus()));
            orderLineSDO.setSubStatusDesc(desc);
        }
        if (orderLine.getMainStatus() != null) {
            String desc = OrderStatus.of(Integer.parseInt(String.valueOf(orderLine.getMainStatus()))).getDesc();
            orderLineSDO.setOrderStatus(String.valueOf(orderLine.getMainStatus()));
            orderLineSDO.setOrderStatusDesc(desc);
        }
        orderLineSDO.setOrderQuantity(orderLine.getSubQuantity() != null ? String.valueOf(orderLine.getSubQuantity()) : null);
        orderLineSDO.setUnitPrice(orderLine.getSubUnitPrice());
        if (orderLine.getSubQuantity() != null && StringUtil.isNotEmpty(orderLine.getSubUnitPrice())) {
            BigDecimal a = new BigDecimal(orderLine.getSubQuantity());
            BigDecimal b = new BigDecimal(orderLine.getSubUnitPrice());
            orderLineSDO.setTotalAmount(String.valueOf(a.multiply(b)));
        }
        orderLineSDO.setShippedAmount(orderLine.getSubDeliveryAmount());
        orderLineSDO.setDeliveryAmount(orderLine.getSubCumulativeDeliveryQuantity());
        orderLineSDO.setFrontOrderId(orderLine.getMainFrontOrderId());
        orderLineSDO.setFrontOrderBizId(orderLine.getMainPreOrderNo());
        orderLineSDO.setForecastOrderLineNo(orderLine.getSubFrontLineNum());
        orderLineSDO.setCustomerReferenceNo(orderLine.getMainCustomerReferenceNo());
        orderLineSDO.setDeliveryMethod(orderLine.getMainTransportModeCode());
        orderLineSDO.setDeliveryMethodName(orderLine.getMainTransportModeName());
        orderLineSDO.setFromSys(orderLine.getMainFromSys());
        orderLineSDO.setSourceOrderNo(orderLine.getMainSourceOrderNo());
        orderLineSDO.setSourceLineNum(orderLine.getSubSourceLineNum());
        //子单创建日期
        if (orderLine.getSubGmtCreate() != null) {
            orderLineSDO.setGmtCreateDate(DateUtils.toDateStr(orderLine.getSubGmtCreate(),DateUtils.DATETIME_FORMAT));
        }
        //子单修改日期
        if (orderLine.getSubGmtModified() != null) {
            orderLineSDO.setGmtModifiedDate(DateUtils.toDateStr(orderLine.getSubGmtModified(),DateUtils.DATETIME_FORMAT));
        }
        //客户期望交货日期
        if (orderLine.getMainCustomerExpectDate() != null) {
            orderLineSDO.setCustomerExpectDate(DateUtils.toDateStr(orderLine.getMainCustomerExpectDate(),DateUtils.DATE_FORMAT));
        }
        //客户采购订单日期
        if (orderLine.getMainCustomerPurchaseDate() != null) {
            orderLineSDO.setCustomerPurchaseDate(DateUtils.toDateStr(orderLine.getMainCustomerPurchaseDate(),DateUtils.DATE_FORMAT));
        }
        //货品生产日期
        if (orderLine.getSubProductationTime() != null) {
            orderLineSDO.setProducteDate(DateUtils.toDateStr(orderLine.getSubProductationTime(),DateUtils.DATE_FORMAT));
        }

        orderLineSDO.setWarehouseCode(orderLine.getMainWareHouseOutCode());
        orderLineSDO.setWarehouseName(orderLine.getMainWareHouseName());
        orderLineSDO.setShippingWarehouseCode(orderLine.getSubShippingWarehouseOutCode());
        orderLineSDO.setShippingWarehouseName(orderLine.getSubShippingWarehouseName());
        orderLineSDO.setReceiveWarehouseCode(orderLine.getSubReceiveWarehouseOutCode());
        orderLineSDO.setReceiveWarehouseName(orderLine.getSubReceiveWarehouseName());
        if (orderLine.getMainBusinessType() != null) {
            orderLineSDO.setBusinessType(orderLine.getMainBusinessType().toString());
        }
        orderLineSDO.setBusinessTypeName(orderLine.getMainBusinessTypeName());
        orderLineSDO.setCreatorId(orderLine.getMainCreator());
        orderLineSDO.setCreatorName(orderLine.getMainCreatorName2());
        orderLineSDO.setCreatorWorkId(orderLine.getMainCreatorCode());
        orderLineSDO.setUpdatorId(orderLine.getMainUpdater());
        orderLineSDO.setUpdatorName(orderLine.getMainModifierName2());
        orderLineSDO.setUpdatorWorkId(orderLine.getMainModifierCode());
        orderLineSDO.setOrderRemark(orderLine.getMainRemark());
        orderLineSDO.setOrderLineRemark(orderLine.getSubRemark());
        //拒绝原因
        orderLineSDO.setRefuseReasonCode(orderLine.getSubRefuseReasonCode());
        orderLineSDO.setRefuseReasonName(orderLine.getSubRefuseReasonName());
        orderLineSDO.setClosed(orderLine.getSubClosed());
        //订单原因
        orderLineSDO.setCreateReasonCode(orderLine.getMainCreateReason());
        orderLineSDO.setCreateReasonName(orderLine.getMainCreateReasonName());
        //活动
        orderLineSDO.setActivityId(orderLine.getSubActivityCode());
        orderLineSDO.setActivityLineNo(orderLine.getSubActivityTermId());
        orderLineSDO.setActivityName(orderLine.getSubActivityName());
        orderLineSDO.setActivityUnitPrice(orderLine.getSubActivityPrice());
        orderLineSDO.setManualPrice(orderLine.getSubManualPrice());
        orderLineSDO.setManualTotalAmount(orderLine.getSubManualTotalAmount());
        //orderLineSDO.setGiftFlag(orderLine.getSubGiftFlag());

        orderLineSDO.setReturnCharacter(orderLine.getSubReturnCharacter());
        orderLineSDO.setDeliveryFactoryCode(orderLine.getSubDeliveryFactoryCode());
        orderLineSDO.setDeliveryStockCode(orderLine.getSubStockCode());
        orderLineSDO.setReceiveFactoryCode(orderLine.getSubReceiveFactoryCode());
        orderLineSDO.setReceiveStockCode(orderLine.getSubReceiveStockCode());
        orderLineSDO.setSyncVersion(orderLine.getSubSyncVersion() != null ? orderLine.getSubSyncVersion().intValue() : null);

        //以下兼容订单共享字段
        //主单features中取值
        if (StringUtils.isNotBlank(orderLine.getMainFeatures())) {
            Map<String, String> mainFeatures = JSONObject.parseObject(orderLine.getMainFeatures(), Map.class);
            if (MapUtils.isNotEmpty(mainFeatures)) {
                if (StringUtils.isBlank(orderLineSDO.getFrontOrderBizId()) && mainFeatures.get(SaleOrderConstants.FRONT_ORDER_BIZ_ID) != null) {
                    orderLineSDO.setFrontOrderBizId(mainFeatures.get(SaleOrderConstants.FRONT_ORDER_BIZ_ID));
                }
            }
        }

        //子单features中取值
        if (StringUtils.isNotBlank(orderLine.getSubFeatures())) {
            Map<String, String> subFeatures = JSONObject.parseObject(orderLine.getSubFeatures(), Map.class);
            if (MapUtils.isNotEmpty(subFeatures)) {
                //预报数量
                if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.FORECAST_QUANTITY))) {
                    orderLineSDO.setForecastQuantity(subFeatures.get(SaleOrderConstants.FORECAST_QUANTITY));
                }
                //预报订单类型编码
                if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.FRONT_ORDER_LINE_TYPE))) {
                    SaleOrderTag forecastSaleOrderTag = SaleOrderTag.of(subFeatures.get(SaleOrderConstants.FRONT_ORDER_LINE_TYPE));
                    if(forecastSaleOrderTag != null){
                        orderLineSDO.setForecastOrderType(forecastSaleOrderTag.getDesc());
                    }
                }
                //SAP库存地点
                if (subFeatures.get(SaleOrderConstants.INVENTORY_CODE) != null) {
                    orderLineSDO.setSAPInventoryPoint(subFeatures.get(SaleOrderConstants.INVENTORY_CODE));
                }
                //SAP工厂编码
                if (subFeatures.get(SaleOrderConstants.FACTORY_CODE) != null) {
                    orderLineSDO.setSAPFactoryCode(subFeatures.get(SaleOrderConstants.FACTORY_CODE));
                }
                //设置活动行号
                if (StringUtils.isNotBlank(subFeatures.get("activityDteails"))) {
                    List<ActivitySDO> activitySDOS = JSONObject.parseArray(subFeatures.get("activityDteails"), ActivitySDO.class);
                    if (CollectionUtils.isNotEmpty(activitySDOS)) {
                        List<String> collectActivityId = activitySDOS.stream().map(ActivitySDO::getActivityCode).collect(Collectors.toList());
                        String activityId = collectActivityId.stream().collect(Collectors.joining("/"));
                        if(StringUtils.isBlank(orderLineSDO.getActivityId()) && StringUtils.isNotBlank(activityId)){
                            orderLineSDO.setActivityId(activityId);
                        }
                        List<String> collectActivityName = activitySDOS.stream().map(ActivitySDO::getActivityName).collect(Collectors.toList());
                        String activityName = collectActivityName.stream().collect(Collectors.joining("/"));
                        if(StringUtils.isBlank(orderLineSDO.getActivityName()) && StringUtils.isNotBlank(activityName)){
                            orderLineSDO.setActivityName(activityName);
                        }
                        List<String> collectActivityNumber = activitySDOS.stream().map(ActivitySDO::getActivityTermid).collect(Collectors.toList());
                        String activityNumber = collectActivityNumber.stream().collect(Collectors.joining("/"));
                        if(StringUtils.isBlank(orderLineSDO.getActivityLineNo()) && StringUtils.isNotBlank(activityNumber)){
                            orderLineSDO.setActivityLineNo(activityNumber);
                        }
                    }
                }
            }
        }
        return orderLineSDO;
    }

}
